package oot.fragment;

import java.util.ArrayList;

import oot.activity.FlashScreenActivity;
import oot.data.Connection;
import oot.data.JSonPaser;
import oot.data.Tweet;
import oot.data.User;
import oot.tab.activity.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import ott.adapter.TweetAdapter;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class HomeFragment extends Fragment {
	private ArrayList<Tweet> listTweets;
	private TweetAdapter adapter;
	private Context mContext;
	private PullToRefreshListView mPullRefreshListView;
	private JSONObject js;
	private String minTweet = "-1";
	private Bundle mBundle;
	private String api;
	private RequestParams params;
	private User mUser;
	private PopupWindow pw;

	public HomeFragment() {
		mUser = FlashScreenActivity.user;
		api = "/timelines/home_timeline";
	}

	public HomeFragment(String api, User user) {
		this.api = api;
		this.mUser = user;
	}

	public User getmUser() {
		return mUser;
	}

	public void setmUser(User mUser) {
		this.mUser = mUser;
	}

	public String getApi() {
		return api;
	}

	public void setApi(String api) {
		this.api = api;
	}

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// api = "/timelines/home_timeline";
		listTweets = new ArrayList<Tweet>();
		mContext = getActivity().getApplicationContext();
		adapter = new TweetAdapter(mContext, listTweets);
	}

	protected void getHomeTimeLine(String userId, String min, String count) {
		params = new RequestParams();
		params.put("user_id", userId);
		params.put("max_tweet_id", min);
		params.put("count", count);
		Log.i("test", "params :" + params.toString());
		Log.i("test", "api :" + api.toString());
		Connection.post(api, params, new AsyncHttpResponseHandler() {
			public void onSuccess(String arg0) {
				Log.i("test", "return --------" + arg0);
				super.onSuccess(arg0);
				try {
					js = new JSONObject(arg0);
					if (js.getInt("status_code") != 0) {
						// show error message if error occur
						Toast toast = Toast.makeText(getActivity()
								.getApplicationContext(), js
								.getString("message"), Toast.LENGTH_SHORT);
						toast.show();
					} else {
						// get timeline
						JSONArray jsTweets = (JSONArray) js.get("entity");

						for (int i = 0; i < jsTweets.length(); i++) {
							// add to list tweet
							listTweets.add(JSonPaser
									.paserTweet((JSONObject) jsTweets.get(i)));
						}

						if (!listTweets.isEmpty())
							minTweet = listTweets.get(listTweets.size() - 1)
									.getTweetId();
						Log.i("test", "min tweetid" + minTweet);
						adapter.notifyDataSetChanged();
						// Call onRefreshComplete when the list has been
						// refreshed.
						mPullRefreshListView.onRefreshComplete();
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void onFailure(Throwable arg0, String arg1) {
				// TODO Auto-generated method stub
				super.onFailure(arg0, arg1);
				Log.i("test", "jumb to onfailure");
				mPullRefreshListView.onRefreshComplete();
			}
		});
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Log.i("test", "run to on resume" + System.currentTimeMillis());
		if (listTweets.size() > 0) {
			listTweets.clear();
		}
		getHomeTimeLine(mUser.getUserID(), "-1", "10");
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View v = inflater.inflate(R.layout.home_layout, container, false);
		View popup = inflater.inflate(R.layout.popup_layout, null);
		pw = new PopupWindow(popup, 300, 20, false);
		mPullRefreshListView = (PullToRefreshListView) v
				.findViewById(R.id.lv_tweet);
		mPullRefreshListView.getRefreshableView().setAdapter(adapter);
		if (mBundle != null) {
			int firstItem = mBundle.getInt("firstelement");
			// Log.i("test","first item "+ firstItem);
			mPullRefreshListView.getRefreshableView().setAdapter(adapter);
			mPullRefreshListView.getRefreshableView().setSelectionFromTop(
					firstItem, 0);
		}
		mPullRefreshListView
				.setOnRefreshListener(new OnRefreshListener<ListView>() {
					@Override
					public void onRefresh(
							PullToRefreshBase<ListView> refreshView) {
						// mPullRefreshListView.setLastUpdatedLabel("Loading...");
						listTweets.clear();
						getHomeTimeLine(mUser.getUserID(), "-1", "10");
					}
				});

		// Add an end-of-list listener
		mPullRefreshListView
				.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {

					@Override
					public void onLastItemVisible() {
						Log.i("test", "last item viewed");
						getHomeTimeLine(mUser.getUserID(), minTweet, "6");
					}
				});
		//mPullRefreshListView.setOn
		mPullRefreshListView.setOnScrollListener(
				new OnScrollListener() {

					@Override
					public void onScrollStateChanged(AbsListView view,
							int scrollState) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onScroll(AbsListView view,
							int firstVisibleItem, int visibleItemCount,
							int totalItemCount) {
						// TODO Auto-generated method stub
						if (pw.isShowing())
							pw.dismiss();
					}
				});
		return v;
	}
}
